//
//  ZORuler.m
//  WaxPatch
//
//  Created by 梁炜东 on 16/4/20.
//  Copyright © 2016年 zerotech.com. All rights reserved.
//

#import "ZYXRuler.h"
#import <math.h>

#define SHEIGHT 8
#define INDICATORCOLOR [UIColor whiteColor].CGColor

@implementation ZYXRuler {
//    ZORulerScrollView * rulerScrollView;
    BOOL isCreate;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.rulerScrollView = [ZYXRulerScrollView new];
        self.rulerScrollView.delegate = self;
        self.rulerScrollView.showsHorizontalScrollIndicator = NO;
        self.rulerScrollView.rulerHeight = frame.size.height;
        self.rulerScrollView.rulerWidth = frame.size.width;
        [self addTagGesture];
        [self drawRacAndLine];
    }
    return self;
}
- (void)addTagGesture{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:tap];

}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    NSInteger currentValue = [self getRulerValue:self.rulerScrollView];
    NSString *key = self.rulerScrollView.arrayText[currentValue];
    if (self.rulerDeletate && [self.rulerDeletate respondsToSelector:@selector(delegateTapRulerCurrentValue:)])
    {
        [self.rulerDeletate delegateTapRulerCurrentValue:key];
    }
}

- (NSInteger)getCurrentRulerValue
{
    NSInteger currentValue = (NSInteger)[self getRulerValue:self.rulerScrollView];
    return currentValue;
}

- (void)showRulerScrollViewWithCount:(NSUInteger)count
                             average:(NSNumber *)average
                        currentValue:(CGFloat)currentValue
                           smallMode:(BOOL)mode {
    self.rulerScrollView.rulerAverage = average;
//    self.rulerScrollView.rulerCount = count;
    self.rulerScrollView.rulerCount = (self.rulerScrollView.arrayText.count - 1)*10;
    self.rulerScrollView.rulerValue = currentValue;
    self.rulerScrollView.mode = mode;
    [self.rulerScrollView drawRuler];
    [self addSubview:self.rulerScrollView];
    [self drawRacAndLineRed];//红色指示器
}
-(void)drawRacAndLineRed
{
    // 红色指示器
    CAShapeLayer *shapeLayerLine = [CAShapeLayer layer];
    shapeLayerLine.strokeColor = [UIColor redColor].CGColor;
    shapeLayerLine.fillColor = [UIColor redColor].CGColor;
    shapeLayerLine.lineWidth = 0.5f;
    shapeLayerLine.lineCap = kCALineCapSquare;
    
    //    NSUInteger ruleHeight = 0; // 文字高度
    CGMutablePathRef pathLine = CGPathCreateMutable();
    CGPathMoveToPoint(pathLine, NULL, self.frame.size.width / 2, DISTANCETOPANDBOTTOM + SHEIGHT - 10);
    CGPathAddLineToPoint(pathLine, NULL, self.frame.size.width / 2, self.frame.size.height);
    shapeLayerLine.shouldRasterize = NO;//抗锯齿参数
    
    shapeLayerLine.path = pathLine;
    [self.layer addSublayer:shapeLayerLine];
    
}
-(void)resetRuler:(NSInteger)value
{
    self.rulerScrollView.rulerValue = value;
    [self.rulerScrollView reset];
}

#pragma mark - ScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    wax_instance_pushUserdata(L, self);
//    lua_getfield(L, -1, WAX_TAPCALLBACK_FUNCTIONNAME);
//    NSInteger currentValue = [self getRulerValue:self.rulerScrollView];
//    NSDictionary *dicValue = @{@"tag" : [NSNumber numberWithInteger:self.tag],
//                               @"currentValue" : [NSNumber numberWithFloat:currentValue]};
//    wax_fromObjc(L, "@", &dicValue);
//    
//    if (wax_pcall(L, 1, 0)) {
//        //        const char* error_string = lua_tostring(L, -1);
//        //        luaL_error(L, "Problem calling Lua function '%s' from wax_socket.\n%s", WAX_SOCKET_READCALLBACK_FUNCTION_NAME, error_string);
//    }
}

- (void)scrollViewDidScroll:(ZYXRulerScrollView *)scrollView {
    CGFloat offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT;
    CGFloat ruleValue = (offSetX / DISTANCEVALUE) * [scrollView.rulerAverage floatValue];
    if (ruleValue < 0.f) {
        return;
    } else if (ruleValue > scrollView.rulerCount * [scrollView.rulerAverage floatValue]) {
        return;
    }
    if (self.rulerDeletate) {
        if (!scrollView.mode) {
            scrollView.rulerValue = ruleValue;
        }
        scrollView.mode = NO;
//        [self.rulerDeletate zoRuler:scrollView];
//        
    }
//    scrollView.rulerValue = ruleValue;
//    NSLog(@"~~~~~~~~~~~~~~~%f", scrollView.rulerValue);
}
- (void)scrollViewDidEndDecelerating:(ZYXRulerScrollView *)scrollView
{
    [self animationRebound:scrollView Decelerate:NO];
}

- (void)scrollViewDidEndDragging:(ZYXRulerScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self animationRebound:scrollView Decelerate:decelerate];
}

- (void)animationRebound:(ZYXRulerScrollView *)scrollView Decelerate:(BOOL)decelerate
{
    CGFloat offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT;
    CGFloat oX = (offSetX / DISTANCEVALUE) * [scrollView.rulerAverage floatValue];
    if ([self valueIsInteger:scrollView.rulerAverage]) {
        oX = [self notRounding:oX afterPoint:0];
    }
    else {
        oX = [self notRounding:oX afterPoint:1];
    }
    CGFloat offX = (oX / ([scrollView.rulerAverage floatValue])) * DISTANCEVALUE + DISTANCELEFTANDRIGHT - self.frame.size.width / 2;
    
    CGFloat ruleValue = [self getRulerValue:scrollView];
    
    NSString *strValue = [NSString stringWithFormat:@"%.0f", ruleValue];
    NSInteger IrulerValue = [strValue integerValue];
    
    offX = -(self.rulerScrollView.rulerWidth / 2.f - DISTANCELEFTANDRIGHT) + IrulerValue*80;
    [UIView animateWithDuration:.2f animations:^{
        scrollView.contentOffset = CGPointMake(offX, 0);
        NSInteger value = (NSInteger)[self getRulerValue:scrollView];
        if (!decelerate)
        {
            if (value >= 0 && value < self.rulerScrollView.arrayText.count)
            {
                NSString *key = self.rulerScrollView.arrayText[value];
                if (self.rulerDeletate && [self.rulerDeletate respondsToSelector:@selector(delegateRulerCurrentValue:)])
                {
                    [self.rulerDeletate delegateRulerCurrentValue:key];
                }
            }
        }
    }];
    
    
    
}

- (CGFloat)getRulerValue:(ZYXRulerScrollView *)scrollView{
    CGFloat offSetXX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT;
    CGFloat ruleValue = (offSetXX / DISTANCEVALUE) * [scrollView.rulerAverage floatValue];
    return ruleValue;
}

- (void)drawRacAndLine {
    // 圆弧
    CAShapeLayer *shapeLayerArc = [CAShapeLayer layer];
    shapeLayerArc.strokeColor = [UIColor lightGrayColor].CGColor;
    shapeLayerArc.fillColor = [UIColor clearColor].CGColor;
    shapeLayerArc.lineWidth = 1.f;
    shapeLayerArc.lineCap = kCALineCapButt;
    shapeLayerArc.frame = self.bounds;
    
    // 渐变
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    
    gradient.colors = @[(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5] colorWithAlphaComponent:0.8f].CGColor,
                        (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5] colorWithAlphaComponent:0.0f].CGColor,
                        (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5] colorWithAlphaComponent:0.8f].CGColor];
//    gradient.colors = @[(id)[UIColor colorWithRed:0 green:0 blue:0 alpha:0.0].CGColor,
//                        (id)[UIColor colorWithRed:0 green:0 blue:0 alpha:0.0].CGColor,
//                        (id)[UIColor colorWithRed:0 green:0 blue:0 alpha:0.0].CGColor];
    gradient.locations = @[[NSNumber numberWithFloat:0.0f],
                           [NSNumber numberWithFloat:0.6f]];
    
    gradient.startPoint = CGPointMake(0, 0.5);
    gradient.endPoint = CGPointMake(1, 0.5);
    
    CGMutablePathRef pathArc = CGPathCreateMutable();
    
//    CGPathMoveToPoint(pathArc, NULL, 0, DISTANCETOPANDBOTTOM + 18+50-20-10);
    CGPathMoveToPoint(pathArc, NULL, 0, self.rulerScrollView.frame.size.height);
    //    CGPathAddQuadCurveToPoint(pathArc, NULL, self.frame.size.width / 2, - 20, self.frame.size.width, DISTANCETOPANDBOTTOM);
    
//    CGPathAddLineToPoint(pathArc, NULL, self.frame.size.width, DISTANCETOPANDBOTTOM + 18+50-20-10);
    CGPathAddLineToPoint(pathArc, NULL, self.frame.size.width, self.rulerScrollView.frame.size.height);
    
    shapeLayerArc.path = pathArc;
    [self.layer addSublayer:shapeLayerArc];
    [self.layer addSublayer:gradient];
    
}

#pragma mark - tool method

- (CGFloat)notRounding:(CGFloat)price afterPoint:(NSInteger)position {
    NSDecimalNumberHandler*roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber*ouncesDecimal;
    NSDecimalNumber*roundedOunces;
    ouncesDecimal = [[NSDecimalNumber alloc]initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [roundedOunces floatValue];
}
- (BOOL)valueIsInteger:(NSNumber *)number {
    NSString *value = [NSString stringWithFormat:@"%f",[number floatValue]];
    if (value != nil) {
        NSString *valueEnd = [[value componentsSeparatedByString:@"."] objectAtIndex:1];
        NSString *temp = nil;
        for(int i =0; i < [valueEnd length]; i++)
        {
            temp = [valueEnd substringWithRange:NSMakeRange(i, 1)];
            if (![temp isEqualToString:@"0"]) {
                return NO;
            }
        }
    }
    return YES;
}




@end
